﻿using System;
using System.Collections.Generic;
using BaiduIndex.Class;
using Newtonsoft.Json;
using System.Web;
using System.Web.Http;
using BaiduIndex.Models;
using HtmlAgilityPack;

namespace BaiduIndex.Controllers
{
    public class SearchController : ApiController
    {
        private const string GetIndexUrl = ApplicationSet.IndexUrl;
        private const string GetCheckUrl = ApplicationSet.CheckUrl;

        /// <summary>
        /// 获取关键词价格
        /// </summary>
        /// <param name="k"></param>
        /// <returns></returns>
        public IHttpActionResult Get(string k)
        {
            try
            {
                //var index = GetSiteIndex(k);
                var index = GetBaiDuIndex(k.Trim());

                return Json(index);
            }
            catch (Exception ex)
            {
                var error = new { status = 10001, data = ex.Message, logid = 0, message = "request block" };
                return Json(error);
            }
        }

        /// <summary>
        /// 爬去百度指数（已失效）
        /// </summary>
        /// <param name="k"></param>
        /// <returns></returns>
        private static object GetBaiDuIndex(string k)
        {
            try
            {

                var maxTryCount = 1;
                RootEmpty index;

                do
                {
                    if (maxTryCount > 20)
                    {
                        return new { status = 10001, data = "", logid = 0, message = "request block" };
                    }

                    var getIndex = string.Format(GetIndexUrl, HttpUtility.HtmlEncode(k));
                    var http = HttpHelper.HttpGet(getIndex);
                    var model = JsonConvert.DeserializeObject<RootEmpty>(http) ?? new RootEmpty();
                    var getModel = model;
                
                    index = getModel;
                    maxTryCount++;
                } while (index.status == 10001);
                
                Console.WriteLine("执行了[" + maxTryCount + "]次");

                return index;
            }
            catch (Exception ex)
            {
                return new RootEmpty() { status = 10001, data = ex.Message, logid = 0, message = "request block" };
            }
        }

        /// <summary>
        /// 爬去站长数据
        /// </summary>
        /// <param name="k"></param>
        /// <returns></returns>
        private static object GetSiteIndex(string k)
        {
            try
            {
                var indexModel = new Root();

                var dataModel = new RootData();

                var itemModel = new GeneralRatioItem();
                var itemList = new List<GeneralRatioItem>();

                var wordModel = new WordItem() { name = k, wordType = 1 };
                var wordItem = new List<WordItem> { wordModel };

                var all = new All();
                var pc = new Pc();
                var wise = new Wise();

                var getIndex = string.Format(GetCheckUrl, HttpUtility.HtmlEncode(k));
                var result = HttpHelper.HttpPost(getIndex);
                HtmlDocument doc = new HtmlDocument();
                doc.LoadHtml(result);
                if (result.IndexOf("<div class=\"z-tc\">抱歉，未找到相关的数据。</div>", StringComparison.Ordinal) >= 0)
                {
                }
                else
                {
                    var xPath1 = "//ul[@class='Module-table-list clearfix']/li[@class='col-88 z-tc']/a[@target='_blank']";
                    var node1 = doc.DocumentNode.SelectNodes(xPath1)[0];
                    var pcIndex1 = node1.InnerHtml;
                    all.avg = Convert.ToInt32(pcIndex1);

                    var xPath2 = "//ul[@class='Module-table-list clearfix']/li[@class='col-99 z-tc']";
                    var node2 = doc.DocumentNode.SelectNodes(xPath2)[0];
                    var pcIndex2 = node2.InnerHtml;
                    pc.avg = Convert.ToInt32(pcIndex2);

                    wise.avg = all.avg - pc.avg;
                }

                itemModel.all = all;
                itemModel.pc = pc;
                itemModel.wise = wise;
                itemModel.word = wordItem;

                itemList.Add(itemModel);
                dataModel.generalRatio = itemList;
                indexModel.data = dataModel;

                return indexModel;
            }
            catch (Exception ex)
            {
                return new RootEmpty() { status = 10001, data = ex.Message, logid = 0, message = "request block" };
            }
        }
    }
}